package controllers

import (
	"fmt"
	"github.com/beego/beego/v2/adapter/logs"
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gomodule/redigo/redis"
	"project/models"
	"strconv"
)

type CartController struct {
	beego.Controller
}

// HandleAddCart 添加购物车
func (this *CartController) HandleAddCart() {
	// 获取数据
	skuid, err1 := this.GetInt("skuid")
	count, err2 := this.GetInt("count")
	resp := make(map[string]interface{})
	// 程序完成后发送JSON
	defer this.ServeJSON()
	// 校验数据
	if err1 != nil || err2 != nil {
		resp["code"] = 1
		resp["msg"] = "传递的数据不正确"
		this.Data["json"] = resp
		return
	}
	userName := this.GetSession("userName")
	if userName == nil {
		resp["code"] = 2
		resp["msg"] = "当前用户未登录"
		this.Data["json"] = resp
		return
	}
	o := orm.NewOrm()
	var user models.User
	user.Name = userName.(string)
	o.Read(&user, "Name")

	// 处理数据
	// 购物车数据储存在redis中，使用hash
	conn, err := redis.Dial("tcp", "192.168.8.136:6379", redis.DialPassword("12345678"))
	defer conn.Close()
	if err != nil {
		logs.Info("redis连接错误")
	}
	// 先获取原来的数量
	preCount, err := redis.Int(conn.Do("hget", "cart_"+strconv.Itoa(user.Id), skuid))
	conn.Do("hset", "cart_"+strconv.Itoa(user.Id), skuid, count+preCount)
	// 获取购物车数量
	rep, err := conn.Do("hlen", "cart_"+strconv.Itoa(user.Id))
	// 回复助手函数
	cartCount, _ := redis.Int(rep, err)
	resp["code"] = 5
	resp["msg"] = "ok"
	resp["cartCount"] = cartCount

	// 返回json数据
	this.Data["json"] = resp

}

// GetCartCount 获取购物车数量
func GetCartCount(this *beego.Controller) int {
	// 从redis中获取购物车数量
	userName := this.GetSession("userName")
	if userName == nil {
		return 0
	}
	o := orm.NewOrm()
	var user models.User
	user.Name = userName.(string)
	o.Read(&user, "Name")
	conn, err := redis.Dial("tcp", "192.168.8.136:6379", redis.DialPassword("12345678"))
	defer conn.Close()
	if err != nil {
		logs.Info("redis连接错误")
		return 0
	}
	rep, err := conn.Do("hlen", "cart_"+strconv.Itoa(user.Id))
	cartCount, _ := redis.Int(rep, err)
	return cartCount
}

// ShowCart 展示购物车页面
func (this *CartController) ShowCart() {
	// 用户信息
	userName := GetUser(&this.Controller)
	// 从redis中获取数据
	conn, err := redis.Dial("tcp", "192.168.8.136:6379", redis.DialPassword("12345678"))
	defer conn.Close()
	if err != nil {
		logs.Info("redis连接错误")
		return
	}

	o := orm.NewOrm()
	var user models.User
	user.Name = userName

	o.Read(&user, "Name")
	goodsMap, _ := redis.IntMap(conn.Do("hgetall", "cart_"+strconv.Itoa(user.Id)))

	goods := make([]map[string]interface{}, len(goodsMap))
	i := 0
	var totalPrice float64
	totalCount := 0
	for index, value := range goodsMap {
		skuid, _ := strconv.Atoi(index)
		var goodsSku models.GoodsSKU
		goodsSku.Id = skuid
		o.Read(&goodsSku)
		temp := make(map[string]interface{})
		temp["goodsSku"] = goodsSku
		temp["count"] = value
		var addPrice float64
		addPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", goodsSku.Price*float64(value)), 64)
		temp["addPrice"] = addPrice
		totalPrice += goodsSku.Price * float64(value)
		totalCount += value
		goods[i] = temp
		i += 1
	}
	this.Data["totalPrice"] = totalPrice
	this.Data["totalCount"] = totalCount
	this.Data["goods"] = goods
	this.TplName = "cart.html"
}

// HandleUpdateCart 更新购物车数据
func (this *CartController) HandleUpdateCart() {
	// 在结算的时候再将数据同步到redis，可以减少服务器的负担，价格计算可以在前端
	// 获取数据
	skuid, err1 := this.GetInt("skuid")
	count, err2 := this.GetInt("count")
	resp := make(map[string]interface{})
	defer this.ServeJSON()
	// 校验数据
	if err1 != nil || err2 != nil {
		resp["code"] = 1
		resp["error"] = "请求数据不正确"
		this.Data["json"] = resp
		return
	}
	userName := this.GetSession("userName")
	if userName == nil {
		resp["code"] = 3
		resp["error"] = "当前用户未登录"
		this.Data["json"] = resp
		return
	}

	o := orm.NewOrm()
	var user models.User
	user.Name = userName.(string)
	o.Read(&user, "Name")
	// 处理数据
	conn, err := redis.Dial("tcp", "192.168.8.136:6379", redis.DialPassword("12345678"))
	defer conn.Close()
	if err != nil {
		resp["code"] = 2
		resp["error"] = "redis数据库连接失败"
		this.Data["json"] = resp
		return
	}
	conn.Do("hset", "cart_"+strconv.Itoa(user.Id), skuid, count)
	resp["code"] = 5
	resp["error"] = "Ok"
	this.Data["json"] = resp
	// 返回数据

}

// DeleteCart 删除购物车数据
func (this *CartController) DeleteCart() {
	// 获取数据
	skuid, err := this.GetInt("skuid")
	resp := make(map[string]interface{})
	defer this.ServeJSON()
	// 校验数据
	if err != nil {
		resp["code"] = 1
		resp["error"] = "请求数据不正确"
		this.Data["json"] = resp
		return
	}
	// 处理数据
	conn, err := redis.Dial("tcp", "192.168.8.136:6379", redis.DialPassword("12345678"))
	defer conn.Close()
	if err != nil {
		resp["code"] = 2
		resp["error"] = "redis数据库连接失败"
		this.Data["json"] = resp
		return
	}
	// 获取userId
	o := orm.NewOrm()
	userName := this.GetSession("userName")
	var user models.User
	user.Name = userName.(string)

	o.Read(&user, "Name")
	conn.Do("hdel", "cart_"+strconv.Itoa(user.Id), skuid)
	// 返回数据
	resp["code"] = 5
	resp["error"] = "OK"
	this.Data["json"] = resp
}
